//
//  KWallViewController.m
//  Keping
//
//  Created by 柯平 on 2017/10/16.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "KWallViewController.h"
#import "KStatusTableViewCell.h"
#import "KStatusRequest.h"
#import "KStatusData.h"
#import "KUserData.h"
#import "KWallDynamicsViewController.h"
#import "KBbsTopicsDetailRequest.h"
#import "KWallNewForDynamicsCell.h"
#import "KWallProfileViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "KTableView.h"
#import "KWallPersonVC.h"
#import "GPVideoCallManager.h"
#import "GPContactRequest.h"
//#import "KStatusDynamicCell.h"
#import "KPhotoGroupView.h"
#import "KWallDetailViewController.h"
#import "KYPhotoBrowserController.h"
#import "KWebViewController.h"
#import "KStatusIsAdTableViewCell.h"

@interface KWallViewController ()<KStatusTableViewCellDelegate, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, KStatusIsAdTableViewCellDelegate>

@property (nonatomic, strong) NSMutableArray *wallNews;
/**底部评论框*/
@property (nonatomic, weak)UITextField*commentField;
@property (nonatomic, strong) KStatusLayout *commentLayout;
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageIndex;

@end

@implementation KWallViewController

-(UITableView *)tableView{
    if (!_tableView) {
        UITableView* tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        tableView.tableHeaderView = [UIView new];//[[UIView alloc]initWithFrame:CGRectZero];
        tableView.tableFooterView = [UIView new];//[[UIView alloc]initWithFrame:CGRectZero];
        tableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        tableView.delegate = self;
        tableView.dataSource = self;
//        tableView.sectionFooterHeight = 0.0;
//        tableView.sectionHeaderHeight = 0.0;
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"Wall";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.data addObject:@"What's happening?"];
    self.tableView.sectionFooterHeight = 10;
    self.tableView.sectionHeaderHeight = CGFLOAT_MIN;
    [self.tableView registerNib:[UINib nibWithNibName:[KWallNewForDynamicsCell className] bundle:nil] forCellReuseIdentifier:[KWallNewForDynamicsCell className]];
    [self.tableView registerClass:[KStatusTableViewCell class] forCellReuseIdentifier:[KStatusTableViewCell className]];
    [self.tableView registerNib:[UINib nibWithNibName:[KStatusIsAdTableViewCell className] bundle:nil] forCellReuseIdentifier:[KStatusIsAdTableViewCell className]];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageIndex = 1;
        [weakSelf getData];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf getData];
    }];
    
    UITextField*commentField=[[UITextField alloc] initWithFrame:CGRectMake(0, self.view.height, self.view.width, 60)];
    [self.view addSubview:commentField];
    commentField.placeholder=@"write a comment";
    commentField.layer.masksToBounds=YES;
    commentField.layer.borderColor=[UIColor colorWithHexString:@"#c1c1c1"].CGColor;
    commentField.backgroundColor = kWhiteColor;
    commentField.layer.borderWidth=1;
    commentField.delegate = self;
    commentField.returnKeyType = UIReturnKeySend;
    commentField.leftView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 25, 40)];
    commentField.leftViewMode=UITextFieldViewModeAlways;
    commentField.hidden = YES;
    self.commentField=commentField;
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView.mj_header beginRefreshing];
}

//-(void)refresh
//{
//    [super refresh];
//    [self getData];
//}
//
//-(void)loadmore
//{
//    [super loadmore];
//    if (self.data.count <= 1)
//        [self refresh];
//    [self getData];
//}

- (NSMutableArray *)wallNews {
    if (!_wallNews) {
        _wallNews = [NSMutableArray new];
    }
    return _wallNews;
}

-(void)getData
{
    [super getData];
    WEAKSELF
    //动态消息提醒
    __block kWallNewMsgRequest *newMsg = [[kWallNewMsgRequest alloc] init];
    
    __block KStatusRequest* request = [[KStatusRequest alloc] init];
    request.params = [NSDictionary dictionaryWithObjectsAndKeys:@(self.pageIndex),@"pageOn", nil];
    NSArray *array;
    if (self.pageIndex == 1) {
        array = @[request, newMsg];
    } else {
        array = @[request];
    }
    
    KBatchRequest *batch = [[KBatchRequest alloc] initWithRequestArray:array];
    [batch startWithCompletionBlockWithSuccess:^(KBatchRequest * _Nonnull batchRequest) {
        if (weakSelf.pageIndex == 1) {
            NSDictionary *newDict = newMsg.responseObject;
            NSInteger wallNewStatu = [[newDict objectForKey:@"statusCode"] integerValue];
            if (wallNewStatu == 200) {
                NSArray *wallNewArr = [newDict objectForKey:@"bbsPostsViews"];
                if (wallNewArr.count > 0) {
                    for (NSDictionary *tmp in wallNewArr) {
                        KStatus *status = [KStatus modelWithDictionary:tmp];
                        if (status) {
                            KStatusLayout *layout = [[KStatusLayout alloc] initWithStatus:status];
                            [weakSelf.wallNews addObject:layout];
                        }
                    }
                }
            }else{
                [self showErrorText:[newDict objectForKey:@"msg"] errCode:wallNewStatu];
            }
        }
        
        NSDictionary *wallDict = request.responseObject;
        NSInteger wallStatu = [[wallDict objectForKey:@"statusCode"] integerValue];
        if (wallStatu == 200) {
            if (weakSelf.pageIndex == 1) {
                [weakSelf.data removeAllObjects];
                [weakSelf.data addObject:@"What's happening?"];
            }
            NSArray *wallArr = [wallDict objectForKey:@"bbsTopicViews"];
            if (wallArr.count > 0) {
                for (NSDictionary *tmp in wallArr) {
                    KStatus *status = [KStatus modelWithDictionary:tmp];
                    if (status) {
                        KStatusLayout *layout = [[KStatusLayout alloc] initWithStatus:status];
                        [weakSelf.data addObject:layout];
                    }
                }
            }
        }else{
            [weakSelf showErrorText:[wallDict objectForKey:@"msg"] errCode:wallStatu];
        }
        if (weakSelf.pageIndex == 1) {
            [weakSelf.tableView.mj_header endRefreshing];
        } else {
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        [weakSelf.tableView reloadData];
    } failure:^(KBatchRequest * _Nonnull batchRequest) {
        if (weakSelf.pageIndex == 1) {
            [weakSelf.tableView.mj_header endRefreshing];
        } else {
            [weakSelf.tableView.mj_footer endRefreshing];
        }
        [weakSelf showError:batchRequest.failedRequest.error];
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.data.count + self.wallNews.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1 && self.wallNews.count > 0) {
        return 0.001;
    }
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if (section == 0) {
        return 54.0;
    }else if (section == 1 && self.wallNews.count > 0) {//(self.wallNews.count >0) {
        return 60.0;
    } else {
        if (self.wallNews.count > 0) {
            KStatusLayout *obj = self.data[section - 1];
            if (obj.status.isAd) {
                KLog(@"cell高度1:%.2f",obj.height);
            }
            
            return obj.height;
        } else {
            KStatusLayout *obj = self.data[section];
            if (obj.status.isAd) {
                KLog(@"cell高度2:%.2f",obj.height);
            }
            return obj.height;
        }
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    if (section == 0) {
        UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
        cell.textLabel.text = @"What's happening?";
        cell.textLabel.font = SystemFont;
        cell.textLabel.textColor = kGrayColor;
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        KPartyView* user = [KPartyView unarchive];
        CGSize size = CGSizeMake(34, 34);
        @weakify(cell);
        [cell.imageView setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",KGetImageURL,user.profile]] placeholder:[[UIImage imageNamed:KImagePlaceholder] imageByResizeToSize:size] options:kNilOptions completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
            if (image) {
                weak_cell.imageView.image = [image imageByResizeToSize:size];
            }
        }];
        return cell;
    } else if (section == 1 && self.wallNews.count > 0) {
        KWallNewForDynamicsCell *new = [tableView dequeueReusableCellWithIdentifier:[KWallNewForDynamicsCell className]];
        new.selectionStyle = UITableViewCellSelectionStyleNone;
        new.wallNews = [self.wallNews copy];
        return new;
    } else {
        KStatusLayout* status;
        if (self.wallNews.count > 0) {
            status = self.data[section - 1];
        } else {
            status = self.data[section];
        }
        if (status.isAd) {
            KStatusIsAdTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[KStatusIsAdTableViewCell className]];
            [cell setStatus:status];
            cell.delegate = self;
            return cell;
        }
        KStatusTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:[KStatusTableViewCell className]];
        cell.delegate = self;
        [cell setLayout:status];
        return cell;
    }
    return nil;
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSInteger section = indexPath.section;
    if (section == 0) {
        KWallDynamicsViewController *notifies = [[KWallDynamicsViewController alloc] initWithNibName:[KWallDynamicsViewController className] bundle:nil];
        [self.navigationController pushViewController:notifies animated:YES];
    } else if (section == 1 && self.wallNews.count > 0) {
        KWallProfileViewController *profile = [[KWallProfileViewController alloc] initWithNibName:[KWallProfileViewController className] bundle:nil];
        profile.statusLayouts = self.wallNews;
        [self.navigationController pushViewController:profile animated:YES];
    } else {
        KStatusLayout* status;
        if (self.wallNews.count > 0) {
            status = self.data[section - 1];
        } else {
            status = self.data[section];
        }
        
        if (status.isAd) {
            KWebViewController *web = [[KWebViewController alloc] init];
            web.requestUrl = status.status.url;
            web.title = status.status.summary;
            [self.navigationController pushViewController:web animated:YES];
        } else {
            return;
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
    textField.hidden = NO;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    if (StringNotNull(textField.text)) {
        [self showErrorText:@"Please enter a comment"];
        return NO;
    }
    kBbsGeneralAndPost *andPost =  [[kBbsGeneralAndPost alloc] init];
    andPost.params = @{
                       @"content":textField.text,
                       @"topicId":self.commentLayout.status.id,
                       @"type":@"to_topic",
                       @"useExperience":@"notice"
                       };
    WEAKSELF
    [andPost startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        [weakSelf hideHUD];
        if (status == 200) {
            weakSelf.commentField.text = nil;
            [weakSelf showSuccess:[dict objectForKey:@"msg"]];
            [weakSelf getData];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf hideHUD];
        [weakSelf showError:request.error];
    }];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    return YES;
}

#pragma mark 键盘通知
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification {
    //获取键盘的高度
    self.commentField.hidden = NO;
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    CGFloat height = keyboardRect.size.height;
    WEAKSELF
    [UIView animateWithDuration:.5 animations:^{
        CGRect rect = weakSelf.commentField.frame;
        rect.origin.y = self.view.height - height + 64 + 74 + 60;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakSelf.commentField.frame = rect;
        });
    } completion:^(BOOL finished) {
    }];
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification {
    [UIView animateWithDuration:.5 animations:^{
        [self.commentField resignFirstResponder];
    } completion:^(BOOL finished) {
        self.commentField.y = self.view.height - 60;
        self.commentField.hidden = YES;
    }];
    
}

#pragma mark KStatusTableViewCellDelegate
- (void)didClickUser:(KStatusLayout *)layout {
}
- (void)didLongClickUser:(KStatusLayout *)layout {
    WEAKSELF
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    //姓名
    UIAlertAction *aciton1 = [UIAlertAction actionWithTitle:StringNotNull(layout.status.realName) ? layout.status.realName : @"" style:UIAlertActionStyleDefault handler:nil];
    //个人信息
    UIAlertAction *aciton2 = [UIAlertAction actionWithTitle:@"View Profile" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        KWallPersonVC *person = [[KWallPersonVC alloc] initWithNibName:[KWallPersonVC className] bundle:nil];
        person.statusLayout = layout;
        [weakSelf.navigationController pushViewController:person animated:YES];
    }];
    //聊天
    UIAlertAction *aciton3 = [UIAlertAction actionWithTitle:@"Voice intercom" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[GPVideoCallManager shareManager] startCall:EMCallTypeVoice username:layout.status.phone ext:nil];
    }];
    //视频聊天
    UIAlertAction *aciton4 = [UIAlertAction actionWithTitle:@"Video intercom" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[GPVideoCallManager shareManager] startCall:EMCallTypeVideo username:layout.status.phone ext:nil];
    }];
    //拨打电话
    NSString *phone;
    if (StringNotNull(layout.status.prix)) {
        phone = [NSString stringWithFormat:@"%@ %@",layout.status.prix,layout.status.phone];
    } else {
        phone = [NSString stringWithFormat:@"%@",layout.status.phone];
    }
    UIAlertAction *aciton5 = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"Phone Call(%@)",phone] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString* str=[NSString stringWithFormat:@"telprompt://%@",phone];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }];
    //拉黑
    UIAlertAction *aciton6 = [UIAlertAction actionWithTitle:@"Block User" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSString *url = [kIMAlterUserInfoURL stringByReplacingOccurrencesOfString:@"{userId}" withString:layout.status.createBy];
        GPContactRequest *request = [[GPContactRequest alloc] initWithURL:url];
        NSString *isBlock = @"Y";
        request.isPost = YES;
        request.params = @{@"isBlock":isBlock};
        WEAKSELF
        [request startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
            NSDictionary *response = request.responseJSONObject;
            if ([response[@"statusCode"] integerValue] != 200) {
                [weakSelf showErrorText:response[@"msg"] errCode:[response[@"statusCode"] integerValue]];
            } else {
                [weakSelf showSuccess:response[@"msg"]];
            }
        } failure:^(__kindof KBaseRequest * _Nonnull request) {
            [weakSelf showError:request.error];
        }];
    }];
    UIAlertAction *aciton7 = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:aciton1];
    [alert addAction:aciton2];
    [alert addAction:aciton3];
    [alert addAction:aciton4];
    [alert addAction:aciton5];
    [alert addAction:aciton6];
    [alert addAction:aciton7];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)didClickLike:(KStatusLayout *)layout {
    kBbsGeneralDetailZanRequest *zanRequest = [[kBbsGeneralDetailZanRequest alloc] init];
    zanRequest.params = @{@"entityId":layout.status.id};
    WEAKSELF
    [zanRequest startWithCompletionBlockWithSuccess:^(__kindof KBaseRequest * _Nonnull request) {
        NSDictionary *dict = request.responseObject;
        NSInteger status = [[dict objectForKey:@"statusCode"] integerValue];
        if (status == 200) {
            [weakSelf showText:[dict objectForKey:@"msg"]];
        } else {
            [weakSelf showErrorText:[dict objectForKey:@"msg"] errCode:status];
        }
    } failure:^(__kindof KBaseRequest * _Nonnull request) {
        [weakSelf showError:request.error];
    }];
}
- (void)didClickComment:(KStatusLayout *)layout {
    _commentLayout = layout;
    [self.commentField becomeFirstResponder];
}

- (void)didClickCommentLabel:(KStatusLayout *)layout {
    if (layout.status.isAd) {
        return;
    } else {
        KWallDetailViewController *detail = [[KWallDetailViewController alloc] init];
        detail.wallID = layout.status.id;
        [self.navigationController pushViewController:detail animated:YES];
    }
    
}

- (void)didClickImages:(KStatusLayout *)layout Index:(NSInteger)index{
    NSMutableArray* items = [NSMutableArray new];
    NSArray* pics = layout.status.imageUrls;
    NSInteger count = pics.count;
    for (NSInteger i = 0, max = count; i < max; i ++ ) {
        NSString* url = pics[i];
        [items addObject:[KGetImageURL stringByAppendingString:url]];
    }
    [KYPhotoBrowserController showPhotoBrowserWithImages:[items copy] currentImageIndex:index delegate:nil];
}

- (void)didClickImagesForWebView:(KStatusLayout *)layout {
    if (layout.status.isAd) {
        KWebViewController *web = [[KWebViewController alloc] init];
        web.requestUrl = layout.status.url;
        web.title = layout.status.summary;
        [self.navigationController pushViewController:web animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
